"""
文章数据模型
"""
from sqlalchemy import Column, String, Text, DateTime, ForeignKey, Enum
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.database import Base
import uuid
import enum


class ArticleStatus(enum.Enum):
    """文章状态枚举"""
    DRAFT = "draft"
    PUBLISHED = "published"
    FAILED = "failed"


class Article(Base):
    """文章模型"""
    
    __tablename__ = "articles"
    
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    theme_id = Column(String(36), ForeignKey("themes.id", ondelete="CASCADE"), nullable=False, comment="关联主题ID")
    title = Column(String(200), nullable=False, comment="文章标题")
    summary = Column(String(500), comment="文章摘要")
    content = Column(Text, nullable=False, comment="文章内容")
    cover_image_id = Column(String(100), comment="封面图片素材ID")
    status = Column(Enum(ArticleStatus), default=ArticleStatus.DRAFT, comment="状态")
    draft_id = Column(String(100), comment="微信草稿ID")
    generated_at = Column(DateTime(timezone=True), server_default=func.now(), comment="生成时间")
    published_at = Column(DateTime(timezone=True), comment="发布时间")
    
    # 关联关系
    theme = relationship("Theme", backref="articles")
    media_assets = relationship("MediaAsset", back_populates="article", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Article(id={self.id}, title={self.title})>"
    
    def to_dict(self):
        """转换为字典"""
        return {
            "id": self.id,
            "theme_id": self.theme_id,
            "title": self.title,
            "summary": self.summary,
            "content": self.content,
            "cover_image_id": self.cover_image_id,
            "status": self.status.value if self.status else None,
            "draft_id": self.draft_id,
            "generated_at": self.generated_at.isoformat() if self.generated_at else None,
            "published_at": self.published_at.isoformat() if self.published_at else None,
            "theme": self.theme.to_dict() if self.theme else None,
        }